package com.itlong.cloud.utils.encrypt;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import java.io.*;

public class TencentUtil {
	public String prefix = "temp";// 创建临时文件
	public String surfix = ".txt";// 后缀
	//TencentECCEngine engine = new TencentECCEngine();

    private static final Logger LOG = LoggerFactory.getLogger(TencentUtil.class);


	/** 创建并验证设备License
	 * 
	 * @param ecKeyFilePath
	 * @param pubKeyFilePath
	 * @param sn
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	public  String createAndCheckLicesnse(String ecKeyFilePath, String pubKeyFilePath, String sn, String projectId,String licencePath)throws Exception {
        //校验ecKey和pubKey是否存在
        if(!(new File(ecKeyFilePath)).exists()){
            LOG.info("ecKeyFilePath:不存在");
        }
        if(!(new File(pubKeyFilePath)).exists()){
            LOG.info("pubKeyFilePath:不存在");
        }

        TencentECCEngine engine = new TencentECCEngine();
        TencentUtil.createDir(licencePath + projectId + "/");
        String guidSnPath = licencePath + projectId + "/" + "guid_" + sn + surfix;
        String licenseFilePath = licencePath + projectId + "/" + sn + surfix;
        TencentUtil.createFile(guidSnPath);
        TencentUtil.writeTxtFile(sn, guidSnPath);
        LOG.info("----guidSnPath: "+guidSnPath+"----licenseFilePath: "+licenseFilePath);
		engine.ECDSASignBufferBase16ToLicenceFile(ecKeyFilePath, sn, licenseFilePath);
		int ret = engine.ECDSAVerifyBase16LicenceFile(pubKeyFilePath, guidSnPath, licenseFilePath);
		if (ret == 1) {
            LOG.info("ecKeyFilePath--"+ecKeyFilePath+"--pubKeyFilePath--"+pubKeyFilePath);
            LOG.info("projectId--"+projectId+"--SN--"+sn+"--生成License验证成功");
			return licenseFilePath;
		} else {
            LOG.info("projectId--"+projectId+"--SN--"+sn+"--生成License验证失败，错误码:" + ret);
			return "";
		}
	}

	// 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败，目标目录已存在！");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            System.out.println("创建目录成功！" + destDirName);
            return true;
        } else {
            System.out.println("创建目录失败！");
            return false;
        }
    }

	// 创建临时文件
    public static String createTempFile(String prefix, String suffix, String dirName) {
        File tempFile = null;
        if (dirName == null) {// 目录如果为空
            try {
                tempFile = File.createTempFile(prefix, suffix);// 在默认文件夹下创建临时文件
                return tempFile.getCanonicalPath();// 返回临时文件的路径
            } catch (IOException e) {// 捕获异常
                e.printStackTrace();
                System.out.println("创建临时文件失败：" + e.getMessage());
                return null;
            }
        } else {
            // 指定目录存在
            File dir = new File(dirName);// 创建目录
            if (!dir.exists()) {
                // 如果目录不存在则创建目录
                if (TencentUtil.createDir(dirName)) {
                    System.out.println("创建临时文件失败，不能创建临时文件所在的目录！");
                    return null;
                }
            }
            try {
                tempFile = File.createTempFile(prefix, suffix, dir);// 在指定目录下创建临时文件
                return tempFile.getCanonicalPath();// 返回临时文件的路径
            } catch (IOException e) {// 捕获异常
                e.printStackTrace();
                System.out.println("创建临时文件失败!" + e.getMessage());
                return null;
            }
        }
    }

    public String readLicenseFile(String licenseFilePath) throws IOException {
		File file = new File(licenseFilePath);
		StringBuilder result = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));//构造一个BufferedReader类来读取文件
        try{
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
            	if (StringUtils.isNotEmpty(s)) {
            		result.append(s);
				}
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            br.close();
        }
        return result.toString();
	}
	/** 创建文件
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static boolean createFile(String filePath) throws Exception {
		File fileName = new File(filePath);
		fileName.setExecutable(true);//设置可执行权限
		fileName.setReadable(true);//设置可读权限
		fileName.setWritable(true);//设置可写权限
		boolean flag = false;
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	/** 写入内容至文件
	 * 
	 * @param content
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static boolean writeTxtFile(String content, String filePath) throws Exception {
		File fileName = new File(filePath);
		boolean flag = false;
		FileOutputStream o = new FileOutputStream(fileName);
		try {
			o.write(content.getBytes("UTF-8"));
			o.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			o.close();
		}
		return flag;
	}
	
	
	
/*	public static void main(String[] arr) throws Exception{
		TencentUtil tencentUtil = new TencentUtil();
		String ecKeyFilePath = "/home/itlong/fileserver/keyfile/1700003415_ec_key.pem";
		String pubKeyFilePath = "/home/itlong/fileserver/keyfile/1700003415_public.pem";
		String sn="0000005800101003";
		String projectId = "00000058";
		tencentUtil.createAndCheckLicesnse(ecKeyFilePath, pubKeyFilePath, sn, projectId);
	}*/
	
	

}
